package com.tcwong.redis.lua;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * Description
 *
 * @author tcwong
 * @date 2021/11/13
 * Since 1.8
 */
@RestController
@RequestMapping("/lua")
public class LuaController {

    @Resource private RedisTemplate redisTemplate;

    private static String REDIS_KEY = "zset:";

    private static Integer SCORE = 1;

    @GetMapping("/add")
    public Object set(){
        LuaBean luaBean = new LuaBean(SCORE,"su"+SCORE,SCORE);
        Boolean add = redisTemplate.opsForZSet().add(REDIS_KEY, luaBean, luaBean.getScore());
        ++SCORE;
        return  add;
    }

    @GetMapping("/get")
    public Object get(){
        return redisTemplate.opsForZSet().range(REDIS_KEY,0,-1);
    }

    @GetMapping("/pop")
    public Object pop(){
        String scriptText = "local object = redis.call('ZRANGE',KEYS[1],0,0);\n" +
                "redis.call('ZREMRANGEBYRANK',KEYS[1],0,0);\n" +
                "return object;";
        DefaultRedisScript<LuaBean> redisScript = new DefaultRedisScript<>();
        redisScript.setResultType(LuaBean.class);
        redisScript.setScriptText(scriptText);
        List<String> keys = new ArrayList<>();
        keys.add(REDIS_KEY);
        Object execute = redisTemplate.execute(redisScript, keys);
        return execute;
    }
}
